﻿SSVC.Utils.Page.IncludeFile("../styles/MessageControl.css", "css");

SSVC.Wrap.Dojo.Require([
    "dojo/_base/fx",
    "dojo/_base/lang",
    "dojo/dom-style",
    "dojo/mouse",
    "dojo/on",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/text!../scripts/MessageControl.html"],

	 SSVC.Wrap.Dojo.Hitch(this,
		function(baseFx, lang, domStyle, mouse, on, _WidgetBase, _TemplatedMixin, template)
		{
			function getMessageFileNameNoExt(filename)
			{
				var lastIndex = filename.lastIndexOf(".");

				return lastIndex > 0 ? filename.substring(0, lastIndex) : filename;
			}

			function getMessagePageNumber(fileMimeType, markupString)
			{
				if (fileMimeType != "application/pdf" || markupString == "")
					return "";
				var xmlDoc = SSVC.Wrap.Dojo.Xml.parse(markupString);
				var page;
				try
				{
					page = xmlDoc.documentElement.getAttribute("page");
				}
				catch (e)
				{
					page = 1;
				}
				return page;
			}

			function getMessageNotationsQuantity(markupString)
			{
				if (markupString == "")
					return "0";

				var xmlDoc = SSVC.Wrap.Dojo.Xml.parse(markupString);
				var count;
				try
				{
					count = xmlDoc.documentElement.childNodes.length;
				}
				catch (e)
				{
					count = 0;
				}
				return count;
			}

			return SSVC.Wrap.Dojo.SetObject("SSVC.UI.MessageControl", SSVC.Wrap.Dojo.Declare([_WidgetBase, _TemplatedMixin, SSVC.UI.TemplateControl], {

				MarkupMessage: null,

				constructor: function(message, displaySourceData, showMessageOnCreation)
				{
					if (!message)
						throw new Error("SSVC.UI.MessageControl: inner exception - message argument can't be null or unefined");
					this.MarkupMessage = message;
					this.ID = message.messageId;
					this.id = message.messageId;
					this.SourceDataKeyedName = message.sourceData.keyed_name;
					this.Classification = message.classification;
					this.MainClass = message.class;
					this.TextContent = message.messageText;
					this.UserName = message.userInfo.first_name + " " + message.userInfo.last_name;
					this.UserID = message.identityFromId;
					this.DateTime = message.messageSentDateTime;
					this.UserOnlineIndicator = message.userOnlineIndicator;
					this.Revision = message.sourceData.revision;
					this.Generation = message.sourceData.generation;
					this.State = message.sourceData.state;
					this.ThumbnailAdditionalStyle = message.thumbnailAdditionalStyle;
					this.SourceDataIcon = message.sourceData.icon_path;
					this.SourseDataTypeName = message.sourceData.type_name;
					this.DisplaySourceData = displaySourceData;
					this.CommunityId = message.communityId;
					this.IdentityFromId = message.identityFromId;
					this.SentDateTimeActual = message.sentDateTimeActual;
					this.ChildrenCount = message.childrenCount;
					this.ShowMessageOnCreation = showMessageOnCreation;
				},

				ReplyWithMarkupLabel: SSVC.Utils.GetResource("mc_reply_markup"),
				ReplyLabel: SSVC.Utils.GetResource("mc_reply"),
				ShowLinkLabel: SSVC.Utils.GetResource("mc_show_only"),
				RepliesState: "",

				// Our template - important!
				templateString: template,

				postCreate: function()
				{
					this.inherited(arguments);

					this.ContentTextNode.innerHTML = this.TextContent.replace(/\n/g, "<br>");
					
					if (this.Classification == "History")
						this.ThumbnailNode.src = "../../" + SSVC.VisualCollaborationTool.Preferences.DeaultHistoryMessageIcon;
					else
						if (this.Classification == "Comment")
							this.ThumbnailNode.src = "../../" + SSVC.VisualCollaborationTool.Preferences.DefaultCommentMessageIcon;
						else
						{
							this.ThumbnailNode.src = top.aras.IomInnovator.getFileUrl(this.MarkupMessage.thumbnailFileID, top.Enums.UrlType.SecurityToken);
							this.imgThumbnailArrowNode.style.display = "inline";

							var resultHTML = "{0}:&nbsp;{1}".Format(SSVC.Utils.GetResource("mc_sm_file"), getMessageFileNameNoExt(this.MarkupMessage.messageFileName));
							var pageNumber = getMessagePageNumber(this.MarkupMessage.messageFileMimeType, this.MarkupMessage.messageMarkup);
							if (pageNumber != "")
								resultHTML += "  {0}:&nbsp;{1}".Format(SSVC.Utils.GetResource("mc_sm_page"), pageNumber);
							resultHTML += "   {0}:&nbsp;{1}".Format(SSVC.Utils.GetResource("mc_sm_notations"), getMessageNotationsQuantity(this.MarkupMessage.messageMarkup));
							this.SnapshotModeInfoContainerNode.innerHTML += resultHTML;
						}

					if (this.ThumbnailAdditionalStyle != "")
					{
						SSVC.Wrap.Dojo.AddClass(this.MessageContainerNode, "tbChildMessageContainer");
						this.imgThumbnailArrowNode.style.left = "46px";
					}
					else
						SSVC.Wrap.Dojo.AddClass(this.MessageContainerNode, "tbMessageContainer");

					if (this.DisplaySourceData)
						this.SourceDataIconNode.src = this.SourceDataIcon;
					else
						this.divSourceDataNode.style.display = "none";

					if (this.ChildrenCount != 0)
					{
						var defRepliesCount = parseInt(SSVC.VisualCollaborationTool.Preferences.DefaultRepliesCount);
						var actualRepliesCount = this.ChildrenCount;
						if (actualRepliesCount <= defRepliesCount)
							if (this.ShowMessageOnCreation)
							{
								this.RepliesState = "A1";
								this.DisplayOfRepliesLink.innerHTML = SSVC.Utils.GetResource("mc_hide_replies");
							}
							else
							{
								this.RepliesState = "A2";
								this.DisplayOfRepliesLink.innerHTML = SSVC.Utils.GetResource("mc_show_replies");
							}
						else
							if (this.ShowMessageOnCreation)
							{
								this.RepliesState = "B1";
								this.DisplayOfRepliesLink.innerHTML = "{0} ({1})".Format(SSVC.Utils.GetResource("mc_show_all_replies"), actualRepliesCount);
							}
							else
							{
								this.RepliesState = "B3";
								this.DisplayOfRepliesLink.innerHTML = SSVC.Utils.GetResource("mc_show_replies");
							}
					}

					if (this.MarkupMessage.parentMessageId && !this.ShowMessageOnCreation)
						this.domNode.style.display = "none";

					this.own(
						on(this.MessageContainerNode, "click", lang.hitch(this, "MessageContainerNode_OnClick", this)),
						on(this.ReplyDropDownImgNode, "click", lang.hitch(this, "DropDownChange", false)),
						on(this.DivReplyNode, "blur", lang.hitch(this, "DropDownChange")),
                        on(this.ReplyNode, "click", lang.hitch(this, "ReplyNode_OnClick", this)),
                        on(this.ReplyWithNode, "click", lang.hitch(this, "ReplyWithNode_OnClick", this)),
						on(this.MessageContainerNode, "mouseover", lang.hitch(this, "ChangeShowLinkVisibility", 1)),
						on(this.MessageContainerNode, "mouseout", lang.hitch(this, "ChangeShowLinkVisibility", 0)),
						on(this.imgThumbnailArrowNode, "click", lang.hitch(this, "ShowSnapshot", this)),
						on(this.DisplayOfRepliesLink, "click", lang.hitch(this, "DisplayOfRepliesLink_OnClick", this.DisplayOfRepliesLink)),
						on(this.UserNameNode, "mouseover", lang.hitch(this, "UserNameNode_OnMouseOver")),
						on(this.UserNameNode, "mouseout", lang.hitch(this, "UserNameNode_OnMouseOut")),
						on(this.DateTimeNode, "mouseover", lang.hitch(this, "DateTimeNode_OnMouseOver")),
						on(this.DateTimeNode, "mouseout", lang.hitch(this, "DateTimeNode_OnMouseOut")),
						on(this.ShowLinkNode, "click", lang.hitch(this, "ShowLinkNode_OnClick")),
						on(this.ThumbnailNode, "click", lang.hitch(this, "ThumbnailNode_OnClick"))
						);

					this.SnapshotMode = false;
				},

				DropDownChange: function(hideOnly)
				{
					if ((this.ReplyWithNode.style.display == "" || this.ReplyWithNode.style.display == "none") & !hideOnly)
						this.ReplyWithNode.style.display = "block";
					else
						this.ReplyWithNode.style.display = "none";
				},

				ChangeShowLinkVisibility: function(newOpacity)
				{
					baseFx.animateProperty(
					{
						node: this.ShowLinkNode,
						properties:
						{
							opacity: newOpacity
						}
					}).play();
				},

				ShowSnapshot: function()
				{
					if (this.SnapshotMode)
					{
						this.HideSnapshot();
						return;
					}

					if (this.MarkupMessage.snapshotFileID == "")
						return;

					var newImageUrl = top.aras.IomInnovator.getFileUrl(this.MarkupMessage.snapshotFileID, top.Enums.UrlType.SecurityToken);
					this.ThumbnailNode.src = newImageUrl;

					var mainContainerRect = this.MainContainerNode.getBoundingClientRect();

					this.divSourceDataNode.style.display = "none";
					this.RightInfoNode.style.display = "none";
					this.SnapshotModeNode.style.width = "174px";
					this.ThumbnailImageContainerNode.style.width = mainContainerRect.width + "px";

					var img = new Image();
					var self = this;
					img.onload = function()
					{
						var newWidth, newHeight;

						newWidth = Math.min(img.width, (mainContainerRect.width - 7));
						newHeight = newWidth / img.width * img.height;

						baseFx.animateProperty(
						{
							node: self.ThumbnailNode,
							properties:
							{
								width: newWidth,
								height: newHeight
							},
							onEnd: function()
							{
								self.SnapshotModeNode.style.height = newHeight + "px";
								self.SnapshotModeNode.style.display = "block";
								self.RightInfoNode.style.display = "inline";
								self.SnapshotModeInfoContainerNode.style.display = "block";
								self.imgThumbnailArrowNode.style.background = "url(../../../images/ThumbnailArrowUp.svg) no-repeat transparent center";
								self.SnapshotMode = true;
							}
						}).play();
					};

					img.src = newImageUrl;
				},

				HideSnapshot: function()
				{
					var newWidth, newHeight;
					if (this.ThumbnailAdditionalStyle != "")
					{
						newWidth = 50;
						newHeight = 50;
					}
					else
					{
						newWidth = 75;
						newHeight = 75;
					}

					this.SnapshotModeNode.style.display = "none";
					this.RightInfoNode.style.display = "none";

					var self = this;
					baseFx.animateProperty(
						{
							node: self.ThumbnailNode,
							properties:
							{
								width: newWidth,
								height: newHeight
							},
							onEnd: function()
							{
								if (self.DisplaySourceData)
									self.divSourceDataNode.style.display = "inline";
								self.RightInfoNode.style.display = "inline";
								self.SnapshotModeInfoContainerNode.style.display = "none";
								self.ThumbnailNode.src = top.aras.IomInnovator.getFileUrl(self.MarkupMessage.thumbnailFileID, top.Enums.UrlType.SecurityToken);
								self.ThumbnailImageContainerNode.style.width = (newWidth + 10) + "px";
								self.imgThumbnailArrowNode.style.background = "url(../../../images/ThumbnailArrow.svg) no-repeat transparent center";
								self.SnapshotMode = false;
							}
						}).play();
				},

				//delegates
				OnReplyClick: function() { },
				OnReplyWithClick: function() { },
				OnDisplayOfRepliesLinkClick: function() { },
				OnUserNameNodeMouseOver: function() { },
				OnUserNameNodeMouseOut: function() { },
				OnDateTimeNodeMouseOver: function() { },
				OnDateTimeNodeMouseOut: function() { },
				OnShowLinkNodeClick: function() { },
				OnMessageContainerNodeClick: function() { },
				OnThumbnailNodeClick: function() { },

				//events
				DisplayOfRepliesLink_OnClick: function()
				{
					this.OnDisplayOfRepliesLinkClick();
				},
				ReplyWithNode_OnClick: function()
				{
					this.OnReplyWithClick(arguments, this);
				},
				ReplyNode_OnClick: function()
				{
					this.OnReplyClick(arguments, this);
					this.DropDownChange(true);
				},
				UserNameNode_OnMouseOver: function()
				{
					this.OnUserNameNodeMouseOver(arguments, this);
				},
				UserNameNode_OnMouseOut: function()
				{
					this.OnUserNameNodeMouseOut(arguments, this);
				},
				DateTimeNode_OnMouseOver: function()
				{
					this.OnDateTimeNodeMouseOver(arguments, this);
				},
				DateTimeNode_OnMouseOut: function()
				{
					this.OnDateTimeNodeMouseOut(arguments, this);
				},
				ShowLinkNode_OnClick: function()
				{
					this.OnShowLinkNodeClick(arguments, this);
				},
				MessageContainerNode_OnClick: function()
				{
					this.OnMessageContainerNodeClick(arguments, this);
				},
				ThumbnailNode_OnClick: function()
				{
					this.OnThumbnailNodeClick();
				}
			}));
		}));